﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;

namespace PhotoList.Dal
{
    public class IO
    {
        #region Attritues

        private static int id = 1;

        private static string[] picType = ConfigurationManager.AppSettings["PicType"].Split(',');
        private static string[] flaType = ConfigurationManager.AppSettings["FlaType"].Split(',');
        private static string[] videoType = ConfigurationManager.AppSettings["VideoType"].Split(',');
        private static string[] audioType = ConfigurationManager.AppSettings["AudioType"].Split(',');
        private static bool isOutPic = ConfigurationManager.AppSettings["IsOutPic"] == "1" ? true : false;
        private static int filenameLenght = Convert.ToInt16(ConfigurationManager.AppSettings["NameLenght"]);

        private static List<string> PicType = new List<string>();
        private static List<string> FlaType = new List<string>();
        private static List<string> VideoType = new List<string>();
        private static List<string> AudioType = new List<string>();

        private static DataTable dt;        

        #endregion

        #region Directory

        /// <summary>
        /// 获取给定路径的子目录列表
        /// </summary>
        /// <param name="path">文件夹路径</param>
        /// <returns>DirectoryInfo[]</returns>
        public static DirectoryInfo[] GetDirectories(string path)
        {
            DirectoryInfo Directories = new DirectoryInfo(path);
            return Directories.GetDirectories();
        }

        /// <summary>
        /// 获取给定路径的子目录列表
        /// </summary>
        /// <param name="path">文件夹路径</param>
        /// <returns>string[]</returns>
        public static string[] GetDirectoriesFullName(string path)
        {
            return Directory.GetDirectories(path);
        }

        /// <summary>
        /// 获取给定路径的子目录列表
        /// </summary>
        /// <param name="path">文件夹路径</param>
        /// <returns>DataTable</returns>
        public static DataTable GetDirectoriesDataTable(string path,int num)
        {
            DirectoryInfo[] Directories = PhotoList.Dal.IO.GetDirectories(new System.Web.UI.Page().Server.MapPath(path));
            int i = 1;

            DataTable dt = new DataTable();
            dt.Columns.Add("id", Type.GetType("System.Int32"));
            dt.Columns[0].AutoIncrement = true;
            dt.Columns[0].AutoIncrementSeed = 1;
            dt.Columns[0].AutoIncrementStep = 1;
            dt.Columns[0].AllowDBNull = false;
            dt.Columns.Add("name", Type.GetType("System.String"));
            dt.Columns[1].AllowDBNull = false;
            dt.Columns.Add("shortname", Type.GetType("System.String"));
            dt.Columns[2].AllowDBNull = false;

            foreach (DirectoryInfo dir in Directories)
            {
                dt.Rows.Add(new object[] { i, dir.ToString(), substring(dir.ToString(), num) });

                i++;
            }

            id = i;

            return dt;
        }

        #endregion

        #region File

        /// <summary>
        /// 获取给定路径的文件列表
        /// </summary>
        /// <param name="path">文件夹路径</param>
        /// <returns>FileInfo[]</returns>
        public static FileInfo[] GetFiles(string path)
        {
            DirectoryInfo Directories = new DirectoryInfo(path);
            return Directories.GetFiles();
        }

        /// <summary>
        /// 获取给定路径的文件列表
        /// </summary>
        /// <param name="path">文件夹路径</param>
        /// <returns>FileInfo[]</returns>
        public static string[] GetFilesFullName(string path)
        {
            return Directory.GetFiles(path);
        }

        /// <summary>
        /// 获取给定路径的文件列表
        /// </summary>
        /// <param name="path">文件夹路径</param>
        /// <returns>DataTable</returns>
        public static DataTable GetFilesDataTable(string path)
        {
            ConvertAppSetting();

            FileInfo[] Files = PhotoList.Dal.IO.GetFiles(new System.Web.UI.Page().Server.MapPath(path));
            int i = id;

            DataTable dt = new DataTable();
            DataColumn dc = null;
            dc = dt.Columns.Add("id", Type.GetType("System.Int32"));
            dc.AutoIncrement = true;
            dc.AutoIncrementSeed = 1;
            dc.AutoIncrementStep = 1;
            dc.AllowDBNull = false;
            dc = dt.Columns.Add("name", Type.GetType("System.String"));
            dc.AllowDBNull = false;
            dc = dt.Columns.Add("shortname", Type.GetType("System.String"));
            dc.AllowDBNull = false;
            dc = dt.Columns.Add("ext", Type.GetType("System.String"));
            dc.AllowDBNull = false;
            dc = dt.Columns.Add("type", Type.GetType("System.String"));
            dc.AllowDBNull = false;

            foreach (FileInfo file in Files)
            {
                if (isOutPic)
                {
                    DataRow dr = dt.NewRow();
                    dr["id"] = i;
                    dr["name"] = file.ToString();
                    dr["shortname"] = substring(file.ToString(), filenameLenght);
                    dr["ext"] = string.IsNullOrEmpty(file.Extension) ? "" : file.Extension.Remove(0, 1);

                    if (PicType.Contains(dr["ext"].ToString().ToLower())) dr["type"] = "0";
                    else if (FlaType.Contains(dr["ext"].ToString().ToLower())) dr["type"] = "1";
                    else if (VideoType.Contains(dr["ext"].ToString().ToLower())) dr["type"] = "2";
                    else if (AudioType.Contains(dr["ext"].ToString().ToLower())) dr["type"] = "3";
                    else dr["type"] = "999";

                    dt.Rows.Add(dr);

                    i++;
                }
                else
                {
                    if (PicType.Contains(string.IsNullOrEmpty(file.Extension) ? "" : file.Extension.Remove(0, 1).ToLower()))
                    {
                        DataRow dr = dt.NewRow();
                        dr["id"] = i;
                        dr["name"] = file.ToString();
                        dr["shortname"] = substring(file.ToString(), filenameLenght);
                        dr["ext"] = file.Extension.Remove(0, 1);
                        dr["type"] = "0";
                        dt.Rows.Add(dr);

                        i++;
                    }
                }
            }

            return dt;
        }

        #endregion

        public static DataTable GetAll(string path)
        {
            ConvertAppSetting();

            DirectoryInfo[] Directories = PhotoList.Dal.IO.GetDirectories(new System.Web.UI.Page().Server.MapPath(path));
            FileInfo[] Files = PhotoList.Dal.IO.GetFiles(new System.Web.UI.Page().Server.MapPath(path));
            int i = 1;

            DataTable dt = new DataTable();

            DataColumn dc = null;
            dc = dt.Columns.Add("id", Type.GetType("System.Int32"));
            dc.AutoIncrement = true;
            dc.AutoIncrementSeed = 1;
            dc.AutoIncrementStep = 1;
            dc.AllowDBNull = false;
            dc = dt.Columns.Add("name", Type.GetType("System.String"));
            dc.AllowDBNull = false;
            dc = dt.Columns.Add("shortname", Type.GetType("System.String"));
            dc.AllowDBNull = false;
            dc = dt.Columns.Add("ext", Type.GetType("System.String"));
            dc.AllowDBNull = false;
            dc = dt.Columns.Add("type", Type.GetType("System.String"));
            dc.AllowDBNull = false;

            foreach(DirectoryInfo dir in Directories)
            {
                dt.Rows.Add(new object[] { i, dir.ToString(), substring(dir.ToString(), filenameLenght), "", "-1" });

                i++;
            }

            foreach(FileInfo file in Files)
            {
                if (isOutPic)
                {
                    DataRow dr = dt.NewRow();
                    dr["id"] = i;
                    dr["name"] = file.ToString();
                    dr["shortname"] = substring(file.ToString(), filenameLenght);
                    dr["ext"] = string.IsNullOrEmpty(file.Extension) ? "" : file.Extension.Remove(0, 1);

                    if (PicType.Contains(dr["ext"].ToString().ToLower())) dr["type"] = "0";
                    else if (FlaType.Contains(dr["ext"].ToString().ToLower())) dr["type"] = "1";
                    else if (VideoType.Contains(dr["ext"].ToString().ToLower())) dr["type"] = "2";
                    else if (AudioType.Contains(dr["ext"].ToString().ToLower())) dr["type"] = "3";
                    else dr["type"] = "999";

                    dt.Rows.Add(dr);

                    i++;
                }
                else
                {
                    if (PicType.Contains(file.Extension == null ? "" : file.Extension.Remove(0, 1).ToLower()))
                    {
                        DataRow dr = dt.NewRow();
                        dr["id"] = i;
                        dr["name"] = file.ToString();
                        dr["shortname"] = substring(file.ToString(), filenameLenght);
                        dr["ext"] = string.IsNullOrEmpty(file.Extension) ? "" : file.Extension.Remove(0, 1);
                        dr["type"] = "0";
                        dt.Rows.Add(dr);

                        i++;
                    }
                }
            }

            return dt;

        }

        public static DataTable Search(string path, string Regular, bool IsFull, bool IsCase, bool IsRegular)
        {
            ConvertAppSetting();

            dt = new DataTable();

            DataColumn dc = null;
            dc = dt.Columns.Add("id", Type.GetType("System.Int32"));
            dc.AutoIncrement = true;
            dc.AutoIncrementSeed = 1;
            dc.AutoIncrementStep = 1;
            dc.AllowDBNull = false;
            dc = dt.Columns.Add("name", Type.GetType("System.String"));
            dc.AllowDBNull = false;
            dc = dt.Columns.Add("shortname", Type.GetType("System.String"));
            dc.AllowDBNull = false;
            dc = dt.Columns.Add("ext", Type.GetType("System.String"));
            dc.AllowDBNull = false;
            dc = dt.Columns.Add("createtime", Type.GetType("System.String"));
            dc.AllowDBNull = false;
            dc = dt.Columns.Add("size", Type.GetType("System.String"));
            dc.AllowDBNull = false;
            dc = dt.Columns.Add("fullpath", Type.GetType("System.String"));
            dc.AllowDBNull = false;
            dc = dt.Columns.Add("type", Type.GetType("System.String"));
            dc.AllowDBNull = false;

            GetAll(path, Regular, IsFull, IsCase, IsRegular);

            return dt;
        }


        public static DataTable GetAll(string path, string Regular, bool IsFull, bool IsCase, bool IsRegular)
        {
            Regex regex = new Regex(@"[a-zA-Z]:\\.+");
            if (!regex.IsMatch(path)) path = new System.Web.UI.Page().Server.MapPath(path);

            DirectoryInfo[] Directories = PhotoList.Dal.IO.GetDirectories(path);
            FileInfo[] Files = PhotoList.Dal.IO.GetFiles(path);
            int i = 1;
            
            string pattern=Regular;
            if (!IsRegular && IsFull)
            {
                pattern = "^" + pattern + "$";
            }
            Regex reg;
            if(IsCase) reg=new Regex(Regular,RegexOptions.IgnoreCase);
            else reg=new Regex(Regular);



            foreach (DirectoryInfo dir in Directories)
            {
                if (reg.IsMatch(dir.Name))
                {
                    dt.Rows.Add(new object[] { i, dir.ToString(), substring(dir.ToString(), filenameLenght), "", dir.CreationTime.ToString("yyyy-MM-dd"), "",dir.FullName, "-1" });
                    i++;
                }

                GetAll(dir.FullName, Regular, IsFull, IsCase, IsRegular);
            }

            foreach (FileInfo file in Files)
            {
                if (!reg.IsMatch(file.Name)) continue;

                if (isOutPic)
                {
                    DataRow dr = dt.NewRow();
                    dr["id"] = i;
                    dr["name"] = file.ToString();
                    dr["shortname"] = substring(file.ToString(), filenameLenght);
                    dr["ext"] = string.IsNullOrEmpty(file.Extension) ? "" : file.Extension.Remove(0, 1);
                    dr["createtime"] = file.CreationTime.ToString("yyyy-MM-dd");
                    dr["size"] = file.Length.ToString();
                    dr["fullpath"] = file.FullName;

                    if (PicType.Contains(dr["ext"].ToString().ToLower())) dr["type"] = "0";
                    else if (FlaType.Contains(dr["ext"].ToString().ToLower())) dr["type"] = "1";
                    else if (VideoType.Contains(dr["ext"].ToString().ToLower())) dr["type"] = "2";
                    else if (AudioType.Contains(dr["ext"].ToString().ToLower())) dr["type"] = "3";
                    else dr["type"] = "999";

                    dt.Rows.Add(dr);

                    i++;
                }
                else
                {
                    if (PicType.Contains(file.Extension == null ? "" : file.Extension.Remove(0, 1).ToLower()))
                    {
                        DataRow dr = dt.NewRow();
                        dr["id"] = i;
                        dr["name"] = file.ToString();
                        dr["shortname"] = substring(file.ToString(), filenameLenght);
                        dr["ext"] = string.IsNullOrEmpty(file.Extension) ? "" : file.Extension.Remove(0, 1);
                        dr["createtime"] = file.CreationTime.ToString("yyyy-MM-dd");
                        dr["size"] = file.Length.ToString();
                        dr["fullpath"] = file.FullName;
                        dr["type"] = "0";
                        dt.Rows.Add(dr);

                        i++;
                    }
                }
            }

            return dt;
        }

        #region String

        public static string substring(string inString, int len)
        {
            string outString = "";
            string tmpString = "";
            int outLen = 0;
            for (int i = 0; i < inString.Length; i++)
            {
                tmpString = inString.Substring(i, 1);
                if (Length(tmpString) == 2) outLen += 2;
                else outLen += 1;
                outString += tmpString;

                if (outLen >= len) break;
            }

            if (outLen < inString.Length) outString += "...";
            return outString;
        }

        private static int Length(string inString)
        {
            if (Regex.IsMatch(inString, @"[^x00-xff]")) return 2;
            else return 1;
        }

        #endregion

        #region Convert

        private static void ConvertAppSetting()
        {
            PicType = ConvertToList(picType);
            FlaType = ConvertToList(flaType);
            VideoType = ConvertToList(videoType);
            AudioType = ConvertToList(audioType);
        }

        private static List<string> ConvertToList(string[] Lists)
        {
            List<string> List = new List<string>();
            for (int i = 0; i < Lists.Length; i++)
            {
                List.Add(Lists[i]);
            }
            return List;
        }

        #endregion
    }
}
